package com.zzq.controller.v2;

import com.zzq.config.FabricK8sInit;
import com.zzq.model.v2.NamespaceEntity;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.NamespaceBuilder;
import io.fabric8.kubernetes.api.model.NamespaceList;
import io.fabric8.kubernetes.api.model.StatusDetails;
import io.fabric8.kubernetes.api.model.storage.StorageClassBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/new/namespace")
@RestController
@Slf4j
public class NewNamespaceController {


    @Autowired
    private KubernetesClient client;

    @GetMapping(value = "/list")
    public List<Namespace> getNamespaceList(){
        //KubernetesClient client = fabricK8sInit.getClient();
        List<Namespace> namespaceList = client.namespaces().list().getItems();
        return namespaceList;
    }


    @GetMapping(value = "/getOne")
    public Namespace getOne(@RequestParam String name){
        //KubernetesClient client = fabricK8sInit.getClient();
        Namespace namespace = client.namespaces().withName(name).item();
        return namespace;
    }

    /**
     * 删除namespace
     * @param namespaceEntity
     * @return
     */
    @PostMapping(value = "/delete")
    public Boolean deleteNamespace(@RequestBody NamespaceEntity namespaceEntity){
        try {
            List<StatusDetails> statusDetails = client.namespaces().withName(namespaceEntity.getName()).delete();
            log.info("删除namespace:{},res:{}",namespaceEntity.getName(),statusDetails.toString());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 创建namespace
     * @return
     */
    @PostMapping(value = "/create")
    public Boolean getNamespaceDetail(@RequestBody NamespaceEntity namespaceEntity){
        try {
            Namespace ns = new NamespaceBuilder()
                    .withNewMetadata()
                    .withName(namespaceEntity.getName())
                    .endMetadata()
                    .build();
            Namespace orReplace = client.namespaces()
                    .createOrReplace(ns);
            log.info("创建了namespace:{}",ns.toString());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
